<template>
  <a-modal
    v-model:open="modalOpen"
    title="选择您感兴趣的标签"
    :width="600"
    :closable="false"
    :mask-closable="false"
    :footer="null"
    :centered="true"
  >
    <div class="tag-selection-container">
      <!-- 说明文字 -->
      <div class="tag-description">
        <p>请选择您感兴趣的标签，这将帮助我们为您推荐更合适的内容</p>
        <p class="sub-text">您可以选择多个标签，选择完成后点击"确认"</p>
      </div>

      <!-- 标签选择区域 -->
      <div class="tag-selection-area">
        <div class="tag-grid">
                     <div
             v-for="tag in availableTags"
             :key="tag.id"
             :class="['tag-item', { selected: selectedTags.includes(tag.id!) }]"
             @click="toggleTag(tag.id!)"
           >
             <div class="tag-content">
               <span class="tag-name">{{ tag.tagName }}</span>
             </div>
           </div>
        </div>
      </div>

      <!-- 已选标签展示 -->
      <div v-if="selectedTags.length > 0" class="selected-tags">
        <h4>已选择的标签：</h4>
        <div class="selected-tags-list">
          <a-tag
            v-for="tagId in selectedTags"
            :key="tagId"
            :color="getTagColor(tagId)"
            closable
            @close="removeTag(tagId)"
          >
            {{ getTagName(tagId) }}
          </a-tag>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="tag-actions">
        <a-button
          type="primary"
          size="large"
          :disabled="selectedTags.length === 0"
          @click="handleConfirm"
          :loading="submitting"
        >
          确认选择 ({{ selectedTags.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { message } from 'ant-design-vue'
import { tagList, saveFirstTag } from '@/api/user/sysTagController'

interface Props {
  open: boolean
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'tag-selection-complete'): void
}

interface SysTag {
  id?: number
  tagName?: string
  color?: string
  icon?: string
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 计算属性用于v-model:open
const modalOpen = computed({
  get: () => props.open,
  set: (value: boolean) => emit('update:open', value)
})

// 可用标签列表
const availableTags = ref<SysTag[]>([])
// 已选择的标签ID列表
const selectedTags = ref<number[]>([])
// 提交状态
const submitting = ref(false)

  // 获取标签列表
  const fetchTags = async () => {
    try {
      const result = await tagList()
      if ((result as any).code === '00000' && result.data) {
        // 将后端返回的数据格式转换为前端需要的格式
        availableTags.value = (result.data as any[]).map(tag => ({
          id: tag.id,
          tagName: tag.tagName,
          color: getTagColor(tag.id) // 根据ID生成颜色
        }))
      } else {
        throw new Error((result as any).msg || '获取标签列表失败')
      }
    } catch (error: any) {
      console.error('获取标签列表失败:', error)
      message.error('获取标签列表失败，请刷新重试')
    }
  }

// 切换标签选择状态
const toggleTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  } else {
    selectedTags.value.push(tagId)
  }
}

// 移除已选标签
const removeTag = (tagId: number) => {
  const index = selectedTags.value.indexOf(tagId)
  if (index > -1) {
    selectedTags.value.splice(index, 1)
  }
}

// 获取标签名称
const getTagName = (tagId: number) => {
  const tag = availableTags.value.find(t => t.id === tagId)
  return tag?.tagName || '未知标签'
}

// 获取标签颜色
const getTagColor = (tagId: number) => {
  const tag = availableTags.value.find(t => t.id === tagId)
  // 如果没有颜色，根据标签ID生成一个固定的颜色
  if (tag?.color) {
    return tag.color
  }
  
  // 根据ID生成不同的颜色
  const colors = ['#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#13c2c2']
  return colors[tagId % colors.length]
}

// 确认选择
const handleConfirm = async () => {
  if (selectedTags.value.length === 0) {
    message.warning('请至少选择一个标签')
    return
  }

  submitting.value = true
  try {
    // 检查token状态
    const token = localStorage.getItem('token')
    console.log('当前token:', token)
    console.log('token长度:', token?.length)
    
    console.log('准备发送的标签数据:', selectedTags.value)
    console.log('标签数据类型:', typeof selectedTags.value)
    console.log('标签数据是否为数组:', Array.isArray(selectedTags.value))
    
    // 尝试不同的数据格式
    let requestData = selectedTags.value
    
    // 如果直接发送数组失败，尝试包装成对象
    if (selectedTags.value.length > 0) {
      // 尝试格式1：直接发送数组
      try {
        const result = await saveFirstTag(selectedTags.value)
        if ((result as any).code === '00000') {
          console.log('标签保存成功:', result)
          message.success('标签选择成功！')
          emit('tag-selection-complete')
          emit('update:open', false)
          return
        } else {
          throw new Error((result as any).msg || '保存标签失败')
        }
      } catch (firstError: any) {
        console.log('直接发送数组失败，尝试包装格式:', firstError.response?.data)
        
        // 尝试格式2：包装成对象
        try {
          const wrappedData = { tagIds: selectedTags.value }
          console.log('尝试包装格式:', wrappedData)
          
          // 这里需要修改API调用，暂时注释掉
          // const result = await saveFirstTag(wrappedData)
          // if ((result as any).code === '00000') {
          //   console.log('标签保存成功:', result)
          //   message.success('标签选择成功！')
          //   emit('tag-selection-complete')
          //   emit('update:open', false)
          //   return
          // }
          
          // 如果包装格式也失败，抛出原始错误
          throw firstError
        } catch (secondError: any) {
          console.log('包装格式也失败:', secondError.response?.data)
          throw firstError
        }
      }
    }
    
    // 如果没有选择标签，不应该到这里
    message.warning('请至少选择一个标签')
    
  } catch (error: any) {
    console.error('保存标签失败:', error)
    console.error('错误详情:', error.response?.data)
    
    // 特殊处理：如果用户已经选择过标签，直接完成登录
    if (error.response?.data?.msg && error.response.data.msg.includes('该用户已经选择过标签')) {
      message.info('您已经选择过标签，正在完成登录...')
      emit('tag-selection-complete')
      emit('update:open', false)
      return
    }
    
    message.error(error.message || '保存标签失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 监听弹窗显示状态，只在显示时获取标签列表
watch(() => props.open, (newOpen) => {
  if (newOpen) {
    fetchTags()
  }
})
</script>

<style scoped>
.tag-selection-container {
  padding: 20px 0;
}

.tag-description {
  text-align: center;
  margin-bottom: 24px;
}

.tag-description p {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.tag-description .sub-text {
  color: #666;
  font-size: 14px;
}

.tag-selection-area {
  margin-bottom: 24px;
}

.tag-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.tag-item {
  padding: 12px 16px;
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  text-align: center;
  background: #fafafa;
}

.tag-item:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.tag-item.selected {
  border-color: #1890ff;
  background: #e6f7ff;
  color: #1890ff;
}

.tag-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.tag-icon {
  font-size: 20px;
}

.tag-name {
  font-size: 14px;
  font-weight: 500;
}

.selected-tags {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.selected-tags h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
}

.selected-tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-actions {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tag-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
    gap: 8px;
  }
  
  .tag-item {
    padding: 8px 12px;
  }
}
</style>
